package com.ljh.filter;

import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.apache.log4j.Logger;

import java.util.concurrent.ConcurrentHashMap;


/**
 * @Author grung
 * @Date 2020/10/9 21:46
 * @Version 1.0
 */

@Activate(group = {"consumer"})
public class TPMonitorFilter implements Filter {

    private static Logger log=Logger.getLogger("TPMonitorFilter"); //日志打印
    private static ConcurrentHashMap<String,MonitorData>m=new ConcurrentHashMap(); //缓存方法调用

    private static long upPrintTime=0; //上次打印时间



    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long startTime = System.currentTimeMillis(); //方法执行开始时间
        Result invoke = invoker.invoke(invocation); //执行方法
        //缓存每个方法的调用情况
        String methodName = invocation.getMethodName();
        MonitorData monitorData = m.get(methodName);
        if(monitorData==null){
            monitorData= MonitorData.getInstance();
        }
        m.put(methodName,monitorData);

        Long endTime = System.currentTimeMillis() - startTime;
        monitorData.addTimesNum(endTime.intValue()); //转成int类型

        //每五秒打印一次
        if(upPrintTime==0 || System.currentTimeMillis()-upPrintTime>=5000) {
            upPrintTime=System.currentTimeMillis();
            int tp50 = monitorData.statTP(0.5F);//统计TP50
            int tp90 = monitorData.statTP(0.9F);//统计TP90
            int tp95 = monitorData.statTP(0.95F);//统计TP95

            System.out.println("__________IP:" + RpcContext.getContext().getRemoteHost()
                    + ", Service:" + invoker.getInterface().getName()
                    + ", Method:" + invocation.getMethodName()
                    + ", requestTotolNum: " + monitorData.getTotalTimes() + " "
                    + ", TP50: " + tp50 + "ms "
                    + ", TP90: " + tp90 + "ms "
                    + ", TP95: " + tp95 + "ms "
            );
        }
        return invoke;
    }
}
